package com.xmy.cultivate.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.merge.LoopMergeStrategy;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.WriteTable;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.xmy.cultivate.entity.*;
import com.xmy.cultivate.enums.StatusSchedulingEnum;
import com.xmy.cultivate.excel.ArrangingExcel;
import com.xmy.cultivate.respons.SchedulingGrade;
import com.xmy.cultivate.service.*;
import com.xmy.cultivate.service.impl.CourseSchedulingServiceImpl;
import com.xmy.cultivate.util.*;
import com.xmy.cultivate.util.DateUtil;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFFont;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.context.annotation.Scope;
import org.springframework.web.bind.annotation.*;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFFont;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.FileOutputStream;
import java.io.IOException;
import java.text.ParseException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * <p>
 * 排课表 前端控制器
 * </p>
 *
 * @author min
 * @since 2022-07-28
 */
@RestController
@RequestMapping("/api/scheduling")
@Scope("prototype")
public class CourseSchedulingController extends BaseController {

    @Autowired
    ICourseSchedulingService iCourseSchedulingService;
    @Autowired
    ICourseSchedulingRedoService iCourseSchedulingRedoService;
    @Autowired
    ICourseSchedulingDetailService iCourseSchedulingDetailService;

    @Autowired
    @Lazy
    IRecordCourseService iRecordCourseService;

    @Autowired
    IDictService iDictService;

    @Autowired
    IClassRoomService iClassRoomService;

    @Autowired
    IGradeService iGradeService;

    @Autowired
    IOrganizationService iOrganizationService;

    @Autowired
    IRepairCourseService iRepairCourseService;

    @Autowired
    IQuarterService iQuarterService;

    @PostMapping()
    public Result save(@RequestBody CourseScheduling courseScheduling) throws ParseException {
        iCourseSchedulingService.saveTo(courseScheduling);
        Grade grade = iGradeService.getById(courseScheduling.getGradeId());
        LocalDate minDate = iCourseSchedulingDetailService.getGradeMinDate(grade.getId());
        LocalDate maxDate = iCourseSchedulingDetailService.getGradeMaxDate(grade.getId());
        grade.setOpenDate(minDate);
        grade.setEndDate(maxDate);
        grade.setIsScheduling(1);
        String timeStart = null;
        String timeEnd = null;
        if (courseScheduling.getArrangingWay().equals(1)){
            timeStart = courseScheduling.getTimeStart();
            timeEnd = courseScheduling.getTimeEnd();
        }else {
            Iterator<CourseSchedulingRedo> iterator = courseScheduling.getRedoList().iterator();
            while (iterator.hasNext()) {
                CourseSchedulingRedo courseSchedulingRedo = iterator.next();
                timeStart = courseSchedulingRedo.getTimeStart();
                timeEnd = courseSchedulingRedo.getTimeEnd();
            }
        }
        grade.setTimeStart(timeStart);
        grade.setTimeEnd(timeEnd);
        iGradeService.updateById(grade);
        return new Result(Code.OK);
    }


    @GetMapping("getListForDate")
    public Result getListForDate(@RequestParam Map reMap,
                                 @RequestParam(value = "teacherIds", defaultValue = "") String[] teacherIds,
                                 @RequestParam(value = "classRooms", defaultValue = "") String[] classRooms,
                                 @RequestParam(value = "yearClassIdList", defaultValue = "") String[] yearClassIdList,
                                 @RequestParam(value = "subjectsIds", defaultValue = "") String[] subjectsIds,
                                 @RequestParam(value = "lessonType", defaultValue = "") String lessonType) {
        QueryWrapper<CourseSchedulingDetail> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("deleted", 0);

        String schoolId = (String) reMap.get("schoolId");
        String isRecord = (String) reMap.get("isRecord");
        String startDate = (String) reMap.get("startDate");
        String endDate = (String) reMap.get("endDate");

        String localDate = LocalDate.now().toString();
        if (StringUtils.isBlank(startDate) || StringUtils.isBlank(endDate)) {
            startDate = localDate;
            endDate = localDate;
        }
        queryWrapper.between("school_date", startDate, endDate);

        if (StringUtils.isNotBlank(schoolId)) {
            queryWrapper.eq("school_id", schoolId);
        } else {
            //queryWrapper.eq("school_id",0L);//没有选择默认为无数据校区
            queryWrapper.in("school_id", this.baseSchoolIdList);
        }


        if (teacherIds.length > 0) {
            queryWrapper.in("teacher_id", teacherIds);
        }
        if (classRooms.length > 0) {
            queryWrapper.in("class_room_id", classRooms);
        }
        if (yearClassIdList.length > 0) {
            queryWrapper.in("year_class_id", yearClassIdList);
        }

        if (subjectsIds.length > 0) {
            queryWrapper.in("subjects_id", subjectsIds);
        }

        if (this.sourseLeve.equals(2)){
            queryWrapper.eq("teacher_id", this.adminId);
        }


        queryWrapper.eq("deleted", 0);
        queryWrapper.eq("grade_status", 1);
        queryWrapper.eq(StringUtils.isNotBlank(lessonType),"lesson_type",lessonType);

        //courseSchedulingDetailQueryWrapper.orderByDesc("")
        List<CourseSchedulingDetail> courseSchedulingDetailList = iCourseSchedulingDetailService.findAll(queryWrapper);

        return new Result(Code.OK, new PageResult(courseSchedulingDetailList, (long) courseSchedulingDetailList.size(), 1L));
    }

    @GetMapping("getListForGrade")
    public Result getListForGrade(@RequestParam Map reMap, @RequestParam(value = "gradeId", defaultValue = "") String gradeId) {
        QueryWrapper<CourseSchedulingDetail> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("deleted", 0);

        String schoolId = (String) reMap.get("schoolId");
        String startDate = (String) reMap.get("startDate");
        String endDate = (String) reMap.get("endDate");

        String localDate = LocalDate.now().toString();
        if (StringUtils.isBlank(startDate) || StringUtils.isBlank(endDate)) {
            startDate = localDate;
            endDate = localDate;
        }
        queryWrapper.between("school_date", startDate, endDate);

        if (StringUtils.isNotBlank(gradeId)) {
            queryWrapper.eq("grade_id", gradeId);
        } else {
            queryWrapper.eq("grade_id", 0);
        }

        //courseSchedulingDetailQueryWrapper.orderByDesc("")
        List<CourseSchedulingDetail> courseSchedulingDetailList = iCourseSchedulingDetailService.findAll(queryWrapper);

        return new Result(Code.OK, new PageResult(courseSchedulingDetailList, (long) courseSchedulingDetailList.size(), 1L));
    }


    @GetMapping("getListForStu")
    public Result getListForStu(@RequestParam Map reMap, @RequestParam(value = "teacherIds", defaultValue = "") String[] teacherIds, @RequestParam(value = "classRooms", defaultValue = "") String[] classRooms, @RequestParam(value = "yearClassIdList", defaultValue = "") String[] yearClassIdList, @RequestParam(value = "subjectsIds", defaultValue = "") String[] subjectsIds, @RequestParam(value = "gradeList", defaultValue = "") String[] gradeList) {
        QueryWrapper<CourseSchedulingDetail> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("deleted", 0);

        String startDate = (String) reMap.get("startDate");
        String endDate = (String) reMap.get("endDate");
        String studentId = (String) reMap.get("studentId");

        String localDate = LocalDate.now().toString();
        if (StringUtils.isBlank(startDate) || StringUtils.isBlank(endDate)) {
            startDate = localDate;
            endDate = localDate;
        }
        queryWrapper.between("school_date", startDate, endDate);

        if (StringUtils.isNotBlank(studentId)) {
            queryWrapper.inSql("grade_id", "select grade_id from student_grade where student_id = " + studentId + " and status = 1 and deleted = 0 and reading_status = 0");
        } else {
            queryWrapper.eq("grade_id", 0);
        }

        //courseSchedulingDetailQueryWrapper.orderByDesc("")
        List<CourseSchedulingDetail> courseSchedulingDetailList = iCourseSchedulingDetailService.findAll(queryWrapper);

        return new Result(Code.OK, new PageResult(courseSchedulingDetailList, (long) courseSchedulingDetailList.size(), 1L));
    }


    @GetMapping("/{id}")
    public Result findById(@PathVariable(value = "id") Long id) {
        CourseSchedulingDetail courseSchedulingDetail = iCourseSchedulingDetailService.getOneById(id);
        //StatusEnum statusEnum = grade.getStatus();
        //System.out.print("statusEnum:"+statusEnum.getStatus());
        return new Result(Code.OK, courseSchedulingDetail);
    }

    @PutMapping("/{id}")
    public Result update(@PathVariable(value = "id") String id, @RequestBody CourseSchedulingDetail courseSchedulingDetail) throws ParseException {

        String date = courseSchedulingDetail.getSchoolDate().toString();
        LocalDateTime startDateTime = DateUtil.StrToDateTime(date + "T" + courseSchedulingDetail.getTimeStart() + ":00");
        LocalDateTime endDateTime = DateUtil.StrToDateTime(date + "T" + courseSchedulingDetail.getTimeEnd() + ":00");
        courseSchedulingDetail.setStartDateTime(startDateTime);
        courseSchedulingDetail.setEndDateTime(endDateTime);
        boolean rs = iCourseSchedulingDetailService.updateById(courseSchedulingDetail);
        return new Result(rs ? Code.OK : Code.ERROR);
    }

    /**
     * 删除排课
     *
     * @param id
     * @return
     */
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable(value = "id") Long id) {
        try {
            QueryWrapper<RecordCourse> recordCourseQueryWrapper = new QueryWrapper<>();
            recordCourseQueryWrapper.eq("scheduling_detail_id", id);
            recordCourseQueryWrapper.eq("deleted", 0);
            Long count = iRecordCourseService.count(recordCourseQueryWrapper);
            if (count > 0) {
                return new Result(Code.ERROR, "", "已存在记上课不能删除");
            }
            boolean rs = iCourseSchedulingDetailService.removeById(id);
            return new Result(rs ? Code.OK : Code.ERROR);
        } catch (Exception e) {
            return new Result(Code.ERROR, e.getMessage());
        }
    }

    /**
     * 批量删除排课
     *
     * @param ids
     * @return
     */
    @DeleteMapping("/deleteBatch/{ids}")
    public Result deleteBatch(@PathVariable(value = "ids") String ids) {
        try {
            if (StringUtils.isNotBlank(ids)) {
                List<Long> idArrDelete = new ArrayList<>();
                String[] idArr = ids.split(",");
                StringBuilder stringBuilder = new StringBuilder();

                for (String id : idArr) {
                    CourseSchedulingDetail courseSchedulingDetail = iCourseSchedulingDetailService.getById(id);

                    QueryWrapper<RecordCourse> recordCourseQueryWrapper = new QueryWrapper<>();
                    recordCourseQueryWrapper.eq("scheduling_detail_id", id);
                    recordCourseQueryWrapper.eq("deleted", 0);
                    Long count = iRecordCourseService.count(recordCourseQueryWrapper);
                    if (count > 0) {
                        stringBuilder.append(courseSchedulingDetail.getGradeName()).append(",");
                        continue;
                    }
                    idArrDelete.add(Long.parseLong(id));
                }

                boolean rs = iCourseSchedulingDetailService.removeBatchByIds(idArrDelete);
                String msg = "删除成功";
                if (StringUtils.isNotBlank(stringBuilder.toString())) {
                    msg = stringBuilder.toString() + "已存在记上课，不能删除，其它删除成功";
                }
                return new Result(rs ? Code.OK : Code.ERROR, "", msg);
            } else {
                return new Result(Code.ERROR, "请选择要删除的数据");
            }
        } catch (Exception e) {
            return new Result(Code.ERROR, e.getMessage());
        }
    }


    /**
     * 获取班级排课学员
     *
     * @return
     */
    @GetMapping("/getStudentForSchedulingGrade")
    public Result getStudentForSchedulingGrade(@RequestParam(value = "schedulingDetailId", defaultValue = "") String schedulingDetailId,@RequestParam(value = "studentName", defaultValue = "") String studentName) {

        CourseSchedulingDetail courseSchedulingDetail = iCourseSchedulingDetailService.getById(schedulingDetailId);
        if (courseSchedulingDetail == null) {
            return new Result(Code.ERROR, "", "排课数据不存在");
        }
        List<Student> studentList = iCourseSchedulingService.getStudentForSchedulingGrade(courseSchedulingDetail.getGradeId().toString(), schedulingDetailId,studentName);
        return new Result(Code.OK, new PageResult(studentList, (long) studentList.size(), 1L));
    }

    @GetMapping("/arrangingList")
    public Result arrangingList(@RequestParam(value = "yearPart", defaultValue = "",required = false) Integer yearPart,
                                @RequestParam(value = "quarterNum", defaultValue = "",required = false) Integer quarterNum,
                                @RequestParam(value = "schoolId", defaultValue = "0",required = false) Long schoolId,
                                @RequestParam(value = "subjectsId", defaultValue = "",required = false) Integer subjectsId,
                                @RequestParam(value = "lessonType", defaultValue = "1") Integer lessonType) {
        if (yearPart == null || quarterNum == null) {
            Quarter quarterNow = iQuarterService.getNowQuarter();
            yearPart = quarterNow.getYearPart();
            quarterNum = quarterNow.getNum();
        }

        //是否假期，0否，1是（假期指的是：寒假、暑假）
        Integer IsVacation = iDictService.getIsVacation(quarterNum);
        List<Map<String, Object>> mapList;

        List<Object> objectList = new ArrayList<>();
        Map<String, Object> map = new HashMap<>();


        String tabHead = "";
        Organization organization = iOrganizationService.getById(schoolId);
        Dict dict = iDictService.getQuarter(quarterNum);
        if (IsVacation.equals(1)) {
            mapList = iCourseSchedulingService.getSchedulingVacation(yearPart, quarterNum, schoolId, subjectsId,lessonType,this.sourseLeve,this.adminId);
            tabHead = organization.getName() + yearPart + "年" + dict.getName() + "课程表";
            map.put("tabHead", tabHead);
            map.put("mapList", mapList);
            objectList.add(map);
        } else {
            mapList = iCourseSchedulingService.getSchedulingTermA(yearPart, quarterNum, schoolId, subjectsId, lessonType,this.sourseLeve,this.adminId);
            tabHead = organization.getName() + yearPart + "年" + dict.getName() + "周内课程表";
            map.put("tabHead", tabHead);
            map.put("mapList", mapList);
            objectList.add(map);
            mapList = iCourseSchedulingService.getSchedulingTermB(yearPart, quarterNum, schoolId, subjectsId,lessonType,this.sourseLeve,this.adminId);
            tabHead = organization.getName() + yearPart + "年" + dict.getName() + "周末课程表";
            map = new HashMap<>();
            map.put("tabHead", tabHead);
            map.put("mapList", mapList);
            objectList.add(map);

        }
        return new Result(Code.OK, objectList, "");
    }

    @GetMapping("/arrangingExcel")
    @ApiOperation("导出课程表格")
    public Result arrangingExcel(@RequestParam(value = "yearPart", defaultValue = "") Integer yearPart,
                                 @RequestParam(value = "quarterNum", defaultValue = "") Integer quarterNum,
                                 @RequestParam(value = "schoolId", defaultValue = "") Long schoolId,
                                 @RequestParam(value = "subjectsId", defaultValue = "") Integer subjectsId,
                                 @RequestParam(value = "lessonType", defaultValue = "1") Integer lessonType) {
        Integer IsVacation = iDictService.getIsVacation(quarterNum);

        List<List<String>> headList = new ArrayList<List<String>>();
        List<String> head0 = new ArrayList<String>();//第一个sheet中的表头
        List<String> head1 = new ArrayList<String>();//第二个sheet中的表头
        List<Map<String, Object>> mapList;
        String tabHead = "";
        Organization organization = iOrganizationService.getById(schoolId);
        Dict dict = iDictService.getQuarter(quarterNum);

        String[] weeks1 = {"", "周一", "周二", "周三", "周四", "周五"};

        List<ClassRoom> classRoomList1 = new ArrayList<>();//周内教室号
        List<ClassRoom> classRoomList2 = new ArrayList<>();//星期六教室号
        List<ClassRoom> classRoomList3 = new ArrayList<>();//星期日教室号
        List<ClassRoom> classRoomList4 = new ArrayList<>();//A天教室号
        List<ClassRoom> classRoomList5 = new ArrayList<>();//B天教室号

        List<SchedulingGrade> timeList1 = new ArrayList<>();//星期六上课时间
        List<SchedulingGrade> timeList2 = new ArrayList<>();//星期天上课时间
        List<SchedulingGrade> timeList3 = new ArrayList<>();//A天上课时间
        List<SchedulingGrade> timeList4 = new ArrayList<>();//B天上课时间

        if (IsVacation.equals(1)) {
            /**
             * A天
             */
            //班级上课时间
            timeList3 = iGradeService.getGradeListForScheduling(schoolId, subjectsId, yearPart, quarterNum, "A",lessonType,this.sourseLeve,this.adminId);

            //教室号
            classRoomList4 = iClassRoomService.getGradeClassRooms1(schoolId, yearPart, quarterNum, "A",lessonType);

            /**
             * B天
             */
            //班级上课时间
            timeList4 = iGradeService.getGradeListForScheduling(schoolId, subjectsId, yearPart, quarterNum, "B",lessonType,this.sourseLeve,this.adminId);

            //教室号
            classRoomList5 = iClassRoomService.getGradeClassRooms1(schoolId, yearPart, quarterNum, "B",lessonType);

            if ((timeList3 != null && classRoomList4 != null) || (timeList4 != null && classRoomList5 != null)) {
                tabHead = organization.getName() + yearPart + "年" + dict.getName() + "课程表";
                head0.add(tabHead);
                headList.add(head0); // 将 head0 添加到 headList 中
            }
        } else {
            /**
             * 周内
             */
            //班级上课时间
            String gradeTime = iGradeService.getGradeTime(schoolId, subjectsId, yearPart, quarterNum, null,lessonType);
            weeks1[0] = gradeTime;

            //教室号
            classRoomList1 = iClassRoomService.getGradeClassRooms(schoolId, yearPart, quarterNum, 0, 6,lessonType);

            if (classRoomList1 != null && gradeTime != null) {
                tabHead = organization.getName() + yearPart + "年" + dict.getName() + "周内课程表";
                head0.add(tabHead); // 将 tabHead 添加到 head0 中
                headList.add(head0); // 将 head0 添加到 headList 中
            }

            /**
             * 星期六
             */
            //班级上课时间
            timeList1 = iGradeService.getGradeListForScheduling(schoolId, subjectsId, yearPart, quarterNum, String.valueOf(6),lessonType,this.sourseLeve,this.adminId);

            //教室号
            classRoomList2 = iClassRoomService.getGradeClassRooms1(schoolId, yearPart, quarterNum, String.valueOf(6),lessonType);

            /**
             * 星期天
             */
            //班级上课时间
            timeList2 = iGradeService.getGradeListForScheduling(schoolId, subjectsId, yearPart, quarterNum, String.valueOf(0),lessonType,this.sourseLeve,this.adminId);

            //教室号
            classRoomList3 = iClassRoomService.getGradeClassRooms1(schoolId, yearPart, quarterNum, String.valueOf(0),lessonType);

            if ((timeList1 != null && classRoomList2 != null) || (timeList2 != null && classRoomList3 != null)) {
                tabHead = organization.getName() + yearPart + "年" + dict.getName() + "周末课程表";
                head1.add(tabHead); // 添加 head1 到 head1 列表中
                headList.add(head1); // 将 head1 添加到 headList 中
            }

        }

        String fileName = "E:/erpImages/uploadFiles/test.xlsx";
        try (Workbook workbook = new XSSFWorkbook()) {
            /**
             * 字体样式
             */
            Font font1 = workbook.createFont();// 创建字体对象
            font1.setBold(true); // 设置字体加粗

            /**
             * 星期样式
             */
            CellStyle cellStyle1 = workbook.createCellStyle();// 创建样式对象
            cellStyle1.setFont(font1);// 将字体应用于样式
            cellStyle1.setFillPattern(FillPatternType.SOLID_FOREGROUND);// 创建填充模式为前景色的样式
            cellStyle1.setFillForegroundColor(IndexedColors.LEMON_CHIFFON.getIndex());// 设置前景色为浅黄色

            /**
             * 课程样式
             */
            CellStyle cellStyle2 = workbook.createCellStyle();// 创建样式对象
            cellStyle2.setFillPattern(FillPatternType.SOLID_FOREGROUND);// 创建填充模式为前景色的样式
            cellStyle2.setFillForegroundColor(IndexedColors.LIGHT_CORNFLOWER_BLUE.getIndex());// 设置前景色为浅紫色

            /**
             * 时间样式
             */
            CellStyle cellStyle3 = workbook.createCellStyle();// 创建样式对象
            cellStyle3.setFont(font1);// 将字体应用于样式
            cellStyle3.setFillPattern(FillPatternType.SOLID_FOREGROUND);// 创建填充模式为前景色的样式
            cellStyle3.setFillForegroundColor(IndexedColors.LIGHT_TURQUOISE.getIndex());// 设置前景色为浅蓝色

            if (IsVacation.equals(1)) {
                /**
                 * 假期
                 */
                for (int i = 0; i < headList.size(); i++) {
                    List<String> head = headList.get(i);
                    String sheetName = head.get(0);
                    Sheet sheet = workbook.createSheet(sheetName);
                    Row row = sheet.createRow(0);

                    // 创建表头，并将每个表头合并为6个单元格
                    Font font2 = workbook.createFont();// 创建字体对象
                    font2.setBold(true); // 设置字体加粗
                    CellStyle style = workbook.createCellStyle();//工作簿样式
                    font2.setFontHeightInPoints((short) 14); // 设置字号为14
                    style.setFont(font1);// 将字体应用于样式
                    style.setAlignment(HorizontalAlignment.CENTER);//设置水平对齐
                    style.setFillPattern(FillPatternType.SOLID_FOREGROUND);// 创建填充模式为前景色的样式
                    style.setFillForegroundColor(IndexedColors.LIGHT_GREEN.getIndex());// 设置前景色为浅绿色
                    Font font = workbook.createFont();
                    font.setBold(true);
                    style.setFont(font);

                    int startIndex = 0; // 开始合并单元格的索引
                    int endIndex = 6; // 结束合并单元格的索引

                    for (String header : head) {
                        Cell cell = row.createCell(startIndex);
                        cell.setCellValue(header);//写入表头
                        cell.setCellStyle(style); // 应用样式
                        sheet.setColumnWidth(startIndex, 6000); // 设置第一列宽
                        sheet.addMergedRegion(new CellRangeAddress(0, 0, startIndex, endIndex - 1));
                        startIndex = endIndex;
                        endIndex += 6;
                    }

                    /**
                     * A天
                     */
                    // 添加a天信息
                    Row timeRow = sheet.createRow(1);
                    Cell weekdayCell = timeRow.createCell(0);
                    weekdayCell.setCellValue("A天");
                    weekdayCell.setCellStyle(cellStyle1); // 应用样式

                    // 添加时间信息
                    int rowIndex = 1; // 行索引从1开始
                    int cellIndex = 1; // 列索引从2开始
                    for (SchedulingGrade schedulingGrade : timeList3) {
                        Row dataRow = sheet.getRow(rowIndex);
                        if (dataRow == null) {
                            dataRow = sheet.createRow(rowIndex);
                        }
                        Cell timeCell = dataRow.createCell(cellIndex);
                        timeCell.setCellValue(schedulingGrade.getSchoolTime());
                        timeCell.setCellStyle(cellStyle1); // 应用样式
                        sheet.setColumnWidth(cellIndex, 8000); // 设置列宽
                        cellIndex++; // 更新列索引
                    }

                    // 添加教室和课程信息
                    rowIndex = 2; // 行索引从2开始
                    for (SchedulingGrade schedulingGrade : timeList3) {
                        int timeIndex = 1; // 列索引从1开始
                        for (ClassRoom classRoom : classRoomList4) {
                            if (classRoom.getGradeName().equals(schedulingGrade.getName())) {
                                Row dataRow = sheet.getRow(rowIndex);
                                if (dataRow == null) {
                                    dataRow = sheet.createRow(rowIndex);
                                }
                                Cell timeCell = dataRow.getCell(0); // 获取教室单元格
                                if (timeCell == null) {
                                    timeCell = dataRow.createCell(0); // 创建教室单元格
                                }
                                timeCell.setCellValue(classRoom.getName()); //写入教室信息
                                timeCell.setCellStyle(cellStyle3); // 应用样式

                                Cell contentCell = dataRow.createCell(timeIndex);
                                contentCell.setCellValue(schedulingGrade.getName()); //写入课程信息
                                contentCell.setCellStyle(cellStyle2); // 应用样式

                            }
                            timeIndex++; // 更新列索引
                        }
                        rowIndex++; // 更新行索引
                    }

                    /**
                     * B天
                     */
                    // 添加b天信息
                    int lastRowIndex = sheet.getLastRowNum(); // 获取最后一条数据的行索引
                    // 最后一条数据的行数（从1开始）
                    int lastDataIndex = lastRowIndex + 2;
                    Row timeRow1 = sheet.createRow(lastDataIndex);
                    Cell weekdayCell1 = timeRow1.createCell(0);
                    weekdayCell1.setCellValue("B天");
                    weekdayCell1.setCellStyle(cellStyle1); // 应用样式

                    // 添加时间信息
                    rowIndex = lastDataIndex; // 行索引从1开始
                    cellIndex = 1; // 列索引从2开始
                    for (SchedulingGrade schedulingGrade : timeList4) {
                        Row dataRow = sheet.getRow(rowIndex);
                        if (dataRow == null) {
                            dataRow = sheet.createRow(rowIndex);
                        }
                        Cell timeCell = dataRow.createCell(cellIndex);
                        timeCell.setCellValue(schedulingGrade.getSchoolTime());
                        timeCell.setCellStyle(cellStyle1); // 应用样式
                        sheet.setColumnWidth(cellIndex, 8000); // 设置列宽
                        cellIndex++; // 更新列索引
                    }

                    // 添加教室和课程信息
                    rowIndex = lastDataIndex + 1; // 行索引从2开始
                    for (SchedulingGrade schedulingGrade : timeList4) {
                        int timeIndex = 1; // 列索引从1开始
                        for (ClassRoom classRoom : classRoomList5) {
                            if (classRoom.getGradeName().equals(schedulingGrade.getName())) {
                                Row dataRow = sheet.getRow(rowIndex);
                                if (dataRow == null) {
                                    dataRow = sheet.createRow(rowIndex);
                                }
                                Cell timeCell = dataRow.getCell(0); // 获取教室单元格
                                if (timeCell == null) {
                                    timeCell = dataRow.createCell(0); // 创建教室单元格
                                }
                                timeCell.setCellValue(classRoom.getName()); //写入教室信息
                                timeCell.setCellStyle(cellStyle3); // 应用样式

                                Cell contentCell = dataRow.createCell(timeIndex);
                                contentCell.setCellValue(schedulingGrade.getName()); //写入课程信息
                                contentCell.setCellStyle(cellStyle2); // 应用样式
                            }
                            timeIndex++; // 更新列索引
                        }
                        rowIndex++; // 更新行索引
                    }

                }
            } else {
                /**
                 * 非假期
                 */
                for (int i = 0; i < headList.size(); i++) {
                    List<String> head = headList.get(i);
                    String sheetName = head.get(0);
                    Sheet sheet = workbook.createSheet(sheetName);
                    Row row = sheet.createRow(0);

                    // 创建表头，并将每个表头合并为6个单元格
                    Font font2 = workbook.createFont();// 创建字体对象
                    font2.setBold(true); // 设置字体加粗
                    CellStyle style = workbook.createCellStyle();//工作簿样式
                    font2.setFontHeightInPoints((short) 14); // 设置字号为14
                    style.setFont(font1);// 将字体应用于样式
                    style.setAlignment(HorizontalAlignment.CENTER);//设置水平对齐
                    style.setFillPattern(FillPatternType.SOLID_FOREGROUND);// 创建填充模式为前景色的样式
                    style.setFillForegroundColor(IndexedColors.LIGHT_GREEN.getIndex());// 设置前景色为浅绿色
                    Font font = workbook.createFont();
                    font.setBold(true);
                    style.setFont(font);

                    int startIndex = 0; // 开始合并单元格的索引
                    int endIndex = 6; // 结束合并单元格的索引

                    for (String header : head) {
                        Cell cell = row.createCell(startIndex);
                        cell.setCellValue(header);//写入表头
                        cell.setCellStyle(style); // 应用样式
                        sheet.setColumnWidth(startIndex, 6000); // 设置第一列宽
                        sheet.addMergedRegion(new CellRangeAddress(0, 0, startIndex, endIndex - 1));
                        startIndex = endIndex;
                        endIndex += 6;
                    }

                    /**
                     * 周内
                     */
                    // 添加时间和星期信息
                    String headCompare1 = head0.toString();
                    headCompare1 = headCompare1.replaceAll("^\\[|]$", "");
                    if (sheetName.equals(headCompare1)) {
                        Row timeRow = sheet.createRow(1);
                        List<String> weekDays = Arrays.asList(weeks1);
                        for (int j = 0; j < weekDays.size(); j++) {
                            Cell weekdayCell = timeRow.createCell(j);
                            weekdayCell.setCellValue(weekDays.get(j));//写入时间和星期
                            weekdayCell.setCellStyle(cellStyle1); // 应用样式
                        }

                        // 添加教室和课程信息
                        int rowIndex = 2; // 行索引从2开始
                        int p = 0;
                        for (ClassRoom classRoom : classRoomList1) {
                            Row dataRow = sheet.createRow(rowIndex++);
                            int cellIndex = 0; // 列索引从0开始
                            Cell classRoomName = dataRow.createCell(cellIndex++);
                            classRoomName.setCellValue(classRoom.getName().toString());//写入教室信息
                            classRoomName.setCellStyle(cellStyle3); // 应用样式
                            sheet.setColumnWidth(p++, 8000); // 设置列宽

                            // 获取课程所属的星期索引
                            String weekIndex = classRoom.getWeekDates();
                            Cell contentCell = dataRow.createCell(Integer.parseInt(weekIndex)); // 找到对应的单元格
                            contentCell.setCellValue(classRoom.getGradeName().toString());//写入课程名称
                            contentCell.setCellStyle(cellStyle2); // 应用样式
                        }
                    }

                    /**
                     * 周末
                     */
                    String headCompare2 = head1.toString();
                    headCompare2 = headCompare2.replaceAll("^\\[|]$", "");
                    if (sheetName.equals(headCompare2)) {

                        /**
                         * 星期六
                         */
                        // 添加星期信息
                        Row timeRow = sheet.createRow(1);
                        Cell weekdayCell = timeRow.createCell(0);
                        weekdayCell.setCellValue("周六");
                        weekdayCell.setCellStyle(cellStyle1); // 应用样式

                        // 添加时间信息
                        int rowIndex = 1; // 行索引从1开始
                        int cellIndex = 1; // 列索引从2开始
                        for (SchedulingGrade schedulingGrade : timeList1) {
                            Row dataRow = sheet.getRow(rowIndex);
                            if (dataRow == null) {
                                dataRow = sheet.createRow(rowIndex);
                            }
                            Cell timeCell = dataRow.createCell(cellIndex);
                            timeCell.setCellValue(schedulingGrade.getSchoolTime());
                            timeCell.setCellStyle(cellStyle1); // 应用样式
                            sheet.setColumnWidth(cellIndex, 8000); // 设置列宽
                            cellIndex++; // 更新列索引
                        }

                        // 添加教室和课程信息
                        rowIndex = 2; // 行索引从2开始
                        for (SchedulingGrade schedulingGrade : timeList1) {
                            int timeIndex = 1; // 列索引从1开始
                            for (ClassRoom classRoom : classRoomList2) {
                                if (classRoom.getGradeName().equals(schedulingGrade.getName())) {
                                    Row dataRow = sheet.getRow(rowIndex);
                                    if (dataRow == null) {
                                        dataRow = sheet.createRow(rowIndex);
                                    }
                                    Cell timeCell = dataRow.getCell(0); // 获取教室单元格
                                    if (timeCell == null) {
                                        timeCell = dataRow.createCell(0); // 创建教室单元格
                                    }
                                    timeCell.setCellValue(classRoom.getName()); //写入教室信息
                                    timeCell.setCellStyle(cellStyle3); // 应用样式

                                    Cell contentCell = dataRow.createCell(timeIndex);
                                    contentCell.setCellValue(schedulingGrade.getName()); //写入课程信息
                                    contentCell.setCellStyle(cellStyle2); // 应用样式

                                }
                                timeIndex++; // 更新列索引
                            }
                            rowIndex++; // 更新行索引
                        }


                        /**
                         * 星期天
                         */
                        int lastRowIndex = sheet.getLastRowNum(); // 获取最后一条数据的行索引
                        // 最后一条数据的行数（从1开始）
                        int lastDataIndex = lastRowIndex + 2;

                        // 添加星期信息
                        Row timeRow1 = sheet.createRow(lastDataIndex);
                        Cell weekdayCell1 = timeRow1.createCell(0);
                        weekdayCell1.setCellValue("周日");
                        weekdayCell1.setCellStyle(cellStyle1); // 应用样式


                        // 添加时间信息
                        rowIndex = lastDataIndex; // 行索引从1开始
                        cellIndex = 1; // 列索引从2开始
                        for (SchedulingGrade schedulingGrade : timeList2) {
                            Row dataRow = sheet.getRow(rowIndex);
                            if (dataRow == null) {
                                dataRow = sheet.createRow(rowIndex);
                            }
                            Cell timeCell = dataRow.createCell(cellIndex);
                            timeCell.setCellValue(schedulingGrade.getSchoolTime());
                            timeCell.setCellStyle(cellStyle1); // 应用样式
                            sheet.setColumnWidth(cellIndex, 8000); // 设置列宽
                            cellIndex++; // 更新列索引
                        }

                        // 添加教室和课程信息
                        rowIndex = lastDataIndex + 1; // 行索引从2开始
                        for (SchedulingGrade schedulingGrade : timeList2) {
                            int timeIndex = 1; // 列索引从1开始
                            for (ClassRoom classRoom : classRoomList3) {
                                if (classRoom.getGradeName().equals(schedulingGrade.getName())) {
                                    Row dataRow = sheet.getRow(rowIndex);
                                    if (dataRow == null) {
                                        dataRow = sheet.createRow(rowIndex);
                                    }
                                    Cell timeCell = dataRow.getCell(0); // 获取教室单元格
                                    if (timeCell == null) {
                                        timeCell = dataRow.createCell(0); // 创建教室单元格
                                    }
                                    timeCell.setCellValue(classRoom.getName()); //写入教室信息
                                    timeCell.setCellStyle(cellStyle3); // 应用样式

                                    Cell contentCell = dataRow.createCell(timeIndex);
                                    contentCell.setCellValue(schedulingGrade.getName()); //写入课程信息
                                    contentCell.setCellStyle(cellStyle2); // 应用样式
                                }
                                timeIndex++; // 更新列索引
                            }
                            rowIndex++; // 更新行索引
                        }
                    }
                }
            }
            try (FileOutputStream fos = new FileOutputStream(fileName)) {
                workbook.write(fos);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return new Result(Code.OK, null, "导出成功");
    }

    /**
     *
     * @param schoolId
     * @param outDateParam
     * @param inDateParam
     * @param lessonType
     * @param type 空为调所以，1只调正常排课的，2调整调课的
     * @return
     * @throws ParseException
     */
    @GetMapping("/melodyCourseForGradeBatch")
    public Result melodyCourseForGradeBatch(@RequestParam("schoolId") Long schoolId,
                                            @RequestParam("outDate") String outDateParam,
                                            @RequestParam("inDate") String inDateParam,
                                            @RequestParam("lessonType") Integer lessonType,
                                            @RequestParam("type") Integer type
                                            ) throws ParseException {

        if (StringUtils.isBlank(outDateParam)) {
            return new Result(Code.ERROR,"","outDate不能为空");
        }

        if (StringUtils.isBlank(inDateParam)) {
            return new Result(Code.ERROR,"","inDate不能为空");
        }

        LocalDate outDate = LocalDate.parse(outDateParam);
        LocalDate inDate = LocalDate.parse(inDateParam);

        iRepairCourseService.melodyCourseForGradeBatch(schoolId,outDate,inDate,lessonType,type);
        return new Result(Code.OK,"","调班中");
    }


    /**
     *
     * @param yearPart
     * @param quarterNum
     * @param schoolId
     * @param subjectsId
     * @param lessonType
     * @param startSchoolDate 开始上课日期
     * @param yearClassId
     * @param type 1添加多少天，2减少多少天
     * @param diffDate 多少天
     * @return
     */
    @GetMapping("/adjustDate")
    public Result adjustDate(@RequestParam("yearPart") Integer yearPart,
                             @RequestParam("quarterNum") Integer quarterNum,
                             @RequestParam(value = "schoolId",required = false) String schoolId,
                             @RequestParam(value = "subjectsId",required = false) String subjectsId,
                             @RequestParam("lessonType") String lessonType,
                             @RequestParam("startSchoolDate") String startSchoolDate,
                             @RequestParam(value = "yearClassId",required = false) String yearClassId,
                             @RequestParam("type") Integer type,
                             @RequestParam("diffDate") Integer diffDate
                             ){
        QueryWrapper<CourseSchedulingDetail> courseSchedulingDetailQueryWrapper = new QueryWrapper<>();
        courseSchedulingDetailQueryWrapper.eq("year_part", yearPart);
        courseSchedulingDetailQueryWrapper.eq("quarter", quarterNum);
        courseSchedulingDetailQueryWrapper.eq("type", 1);//正常排课
        courseSchedulingDetailQueryWrapper.eq(StringUtils.isNotBlank(schoolId),"school_id", schoolId);
        courseSchedulingDetailQueryWrapper.eq(StringUtils.isNotBlank(subjectsId),"subjects_id", subjectsId);
        courseSchedulingDetailQueryWrapper.in("status", 0);
        courseSchedulingDetailQueryWrapper.ge("school_date", startSchoolDate);
        //courseSchedulingDetailQueryWrapper.between("start_date_time", "2024-09-14 00:00:00:","2024-09-14 23:00:00:");
        courseSchedulingDetailQueryWrapper.in("lesson_type",lessonType);
        if (StringUtils.isNotBlank(yearClassId)) {
            courseSchedulingDetailQueryWrapper.inSql("grade_id","select id from grade where year_part="+yearPart+" and quarter_num="+quarterNum+" and lesson_type=1 and year_class_id="+yearClassId);
        }
        //courseSchedulingDetailQueryWrapper.ge("created_at","2024-07-11 11:00:00");//下一次开始时间
        List<CourseSchedulingDetail> courseSchedulingDetailList = iCourseSchedulingDetailService.list(courseSchedulingDetailQueryWrapper);
        Integer i = 0;
        for (CourseSchedulingDetail courseSchedulingDetail : courseSchedulingDetailList) {
            LocalDate localDate = courseSchedulingDetail.getSchoolDate();
            //localDate = localDate.plusDays(1);
            if (type.equals(1)){
                localDate = localDate.plusDays(diffDate);
            }else {
                localDate = localDate.minusDays(diffDate);
            }

            String startDateTime = localDate + "T" + courseSchedulingDetail.getTimeStart() + ":00";
            String endDateTime = localDate + "T" + courseSchedulingDetail.getTimeEnd() + ":00";
            courseSchedulingDetail.setStartDateTime(LocalDateTime.parse(startDateTime));
            courseSchedulingDetail.setEndDateTime(LocalDateTime.parse(endDateTime));
            courseSchedulingDetail.setSchoolDate(localDate);
            courseSchedulingDetail.setType(1);
            //courseSchedulingDetail.setId(idWorker.nextId());
            courseSchedulingDetail.setStatus(StatusSchedulingEnum.NO);
            iCourseSchedulingDetailService.updateById(courseSchedulingDetail);
            System.out.println("i:" + i++);
        }

        return new Result(Code.OK,"","成功");
    }

}
